<style lang="less">
    @import './preview.less';
    // @import './answer.less';
</style>
<template>
  <Layout>
    <Sider :width="300" :style="{position: 'fixed', height: '100vh', right: 0, overflow: 'auto', background: '#EFF0F0', padding: '10px'}">
      <div class="answer-time"style="font-size: 18px;font-weight: bold;">
				<!-- <img src="../../images/stop.png"/> -->
				考试剩余时间：{{time}}
			</div>
      <div class="" v-for="(item, index) in data.tests" v-if="item.length > 0">
        <p >
          <span>{{index === 0 ? '单选题' : (index === 1 ? '多选题' : '判断题')}}
          </span>
          &nbsp;&nbsp;&nbsp;
        </p>
        <div class="" v-for="(i, tindex) in item" :key="getTestIndex(index, tindex)">
          <div class="">
            <p :id="getTestIndex(index, tindex)" @click="maoselect(data.tests,index, tindex)">
              {{getTestIndex(index, tindex)}}.&nbsp;&nbsp;&nbsp;
              {{showSort(i.stuquesans)}}
            </p>
          </div>
          <!-- <p v-if="i.newquestionans" :class="{cr: i.newquestionans !== i.quesans}">考生答案：{{i.newquestionans}}</p> -->
        </div>
      </div>
      <button type="button" style="width:200px;height:30px;background-color:red;"class="ivu-btn ivu-btn-primary" @click="beforFinish()">
        <span>提前交卷</span>
      </button>
    </Sider>
  <div id="body" class="preview-container" :style="{marginRight: '300px'}">
    <!-- 试题本身内容 -->
    <div class="preview-content-container">
      <!-- 每种类型 -->
      <div  class="preview-content-type" v-for="(item, index) in data.tests" v-if="item.length > 0">
        <p >
          <span>{{index === 0 ? '单选题' : (index === 1 ? '多选题' : '判断题')}}
            {{getTotalScore(index)}}分
          </span>
          &nbsp;&nbsp;&nbsp;
        </p>
        <div :id="idgetTestIndex(data.tests,index, tindex)" v-for="(i, tindex) in item">
          <h3>
            <span >{{getTestIndex(index, tindex)}}.&nbsp;&nbsp;&nbsp;{{i.questitle}}</span>
            <span>(每题{{i.questionscore}}分 共 {{item.length}}题)</span>
          </h3>
          <div class="">
            <p style="position: relative;">
              <input :class="[index === '1' || index === 1 ? 'magic-checkbox' : 'magic-radio']"
              :type="index === 1 || index === '1' ? 'checkbox':'radio'  "
              :name="'baoxou' + index + tindex" value="A" v-model="data.tests[index][tindex].stuquesans">
              A: {{i.quessel1}}
            </p>
            <p>
              <input :class="[index === '1' || index === 1 ? 'magic-checkbox' : 'magic-radio']"
              :type="index === 1 || index === '1' ? 'checkbox':'radio' "
              :name="'baoxou' + index + tindex" value="B" v-model="data.tests[index][tindex].stuquesans">
              B: {{i.quessel2}}
            </p>
            <p v-if="i.quessel3">
              <input :class="[index === '1' || index === 1 ? 'magic-checkbox' : 'magic-radio']"
              :type="index === 1 || index === '1' ? 'checkbox':'radio' "
              :name="'baoxou' + index + tindex" value="C" v-model="data.tests[index][tindex].stuquesans">
              C: {{i.quessel3}}
            </p>
            <p v-if="i.quessel4">
              <input :class="[index === '1' || index === 1 ? 'magic-checkbox' : 'magic-radio']"
              :type="index === 1 || index === '1' ? 'checkbox':'radio' "
              :name="'baoxou' + index + tindex" value="D" v-model="data.tests[index][tindex].stuquesans">
              D: {{i.quessel4}}
            </p>
            <p v-if="i.quessel5">
              <input :class="[index === '1' || index === 1 ? 'magic-checkbox' : 'magic-radio']"
              :type="index === 1 || index === '1' ? 'checkbox':'radio' "
              :name="'baoxou' + index + tindex" value="E" v-model="data.tests[index][tindex].stuquesans">
              E: {{i.quessel5}}
            </p>
            <p v-if="i.quessel6">
              <input :class="[index === '1' || index === 1 ? 'magic-checkbox' : 'magic-radio']"
              :type="index === 1 || index === '1' ? 'checkbox':'radio' "
              :name="'baoxou' + index + tindex" value="F" v-model="data.tests[index][tindex].stuquesans">
              F: {{i.quessel6}}
            </p>
            <p v-if="i.quessel7">
              <input :class="[index === '1' || index === 1 ? 'magic-checkbox' : 'magic-radio']"
              :type="index === 1 || index === '1' ? 'checkbox':'radio' "
              :name="'baoxou' + index + tindex" value="G" v-model="data.tests[index][tindex].stuquesans">
              G: {{i.quessel7}}
            </p>
            <p v-if="i.quessel8">
              <input :class="[index === '1' || index === 1 ? 'magic-checkbox' : 'magic-radio']"
              :type="index === 1 || index === '1' ? 'checkbox':'radio' "
              :name="'baoxou' + index + tindex" value="H" v-model="data.tests[index][tindex].stuquesans">
              H: {{i.quessel8}}
            </p>
            <p v-if="i.quessel9">
              <input :class="[index === '1' || index === 1 ? 'magic-checkbox' : 'magic-radio']"
              :type="index === 1 || index === '1' ? 'checkbox':'radio' "
              :name="'baoxou' + index + tindex" value="I" v-model="data.tests[index][tindex].stuquesans">
              I: {{i.quessel9}}
            </p>
          </div>
          <!-- <p v-if="i.newquestionans" :class="{cr: i.newquestionans !== i.quesans}">考生答案：{{i.newquestionans}}</p> -->
        </div>
      </div>
    </div>
  </div>
  <!-- 右侧答案区 -->

</Layout>
</template>

<script>
import Cookies from 'js-cookie';
import axios from 'axios'
// import paperPeopleSet from './paper-people-set.vue'

export default {
  name: 'parper-answer',
  data () {
    return {
      questions: 100,
      currentIndex: 1,
      timer: null,
      loading: false,
      time: '60:00',
      data: {
        tests: []
      },
    };
  },
  mounted () {
    // 记录开始答题时间
    this.data.modelstartdate = this.$formatDateTime()
  },
  methods: {
    // 下一题
    nextQus () {
      // 进度加1，下一题准备
      this.currentIndex += 1;
    },
    // 选中某一个题目，注意选中的为真是下标，需要加1
    selected (index) {
      // console.log('111111111111', index);
      this.currentIndex = index + 1;
    },
    // 提前交卷
    beforFinish () {
      this.$Modal.confirm({
        title: '交卷提醒',
        content: '提前交卷前，请先仔细检查！',
        onOk: () => {
          this.comfirm()
        },
        onCancel: () => {
          console.log('取消提前交卷');
        }
      });
    },
    // 交卷
    comfirm () {
      this.loading = true
      this.$lsdelete('studata')
      let answer = []
      this.data.tests.forEach(arr => {
        arr.forEach(item => {
          answer.push({questionid:item.id,questionnum: item.questionnum, quesans: item.quesans, questionscore: item.questionscore,
            stuquesans: this.answet2string(item.questype.trim(), item.stuquesans.trim())})
        })
        // console.log("学生答案"+this.answet2string(item.questype.trim(), item.stuquesans));
        // answer.push({questionid:item.id,questionnum: item.questionnum, quesans: item.quesans, questionscore: item.questionscore,
        //   stuquesans: this.answet2string(item.questype.trim(), item.stuquesans)})
      })
      let obj = {
        emal: this.data.emal,
        examnum: this.data.examnum,
        idnumber: this.data.idnumber,
        userid: this.data.userid,
        username: this.data.username,
        userphone: this.data.userphone,
        testid: this.data.testid,
        answertimelong: this.getAnswerTime(), // 答题时长
        tests: answer
      }
      // 有testmodelid模拟考试
      if (this.data.testmodelid) {
        obj.modelstartdate = this.data.modelstartdate
        obj.testid = this.data.testmodelid
        obj.modelenddate = this.$formatDateTime()
        obj.modelstatus = '1'
        obj.modelflag = '1'
        obj.modeltestid = this.data.modeltestid
        obj.answertimelong = this.getAnswerTime()
        axios.post('rs/logic/modelcalculfraction', {data: obj}).then(res => {
          if (res.data.code === 200) {
            this.data.result = res.data
            this.$router.replace({
              name: 'score',
              params: this.data
            });
            this.$lsdelete('studata')
          }
        }).catch((error) => {
          this.$Message.error('提交失败,失败原因' + JSON.stringify(error));
        }).finally(() => {
          this.loading = false
        })
      } else { // 正式考试
        axios.post('rs/logic/calculfraction', {data: obj}).then(res => {
          if (res.data.code === 200) {
            this.data.result = res.data
            this.$router.replace({
              name: 'score',
              params: this.data
            });
            this.$lsdelete('studata')
          }
        }).catch((error) => {
          this.$Message.error('提交失败,失败原因' + JSON.stringify(error));
        }).finally(() => {
          this.loading = false
        })
      }


    },
    getAnswerTime () {
      let min = parseInt(this.time.split(':')[0])
      let s = parseInt(this.time.split(':')[1])
      if (s > 0) {
        return `${parseInt(this.data.usertest.testtimelong) - min - 1}分${60-s}秒`
      }
      return `${parseInt(this.data.usertest.testtimelong) - min}分0秒`
    },
    answet2string (type, sq) {
      if (type === '单选题') {
        if (sq.length > 0) {
          return sq
        } else {
          return ''
        }
      } else if (type === '多选题') {
        if (sq.length > 0) {
          return sq.sort().toString()
        } else {
          return ''
        }
      } else if (type === '判断题') {
        if (sq === 'A') {
          return '正确'
        }
        else if (sq === 'B') {
          return '错误'
        }
        else {
          return ''
        }
      }
    },
    showSort(arr) {
      if (arr.length > 1) {
        let newArr = [...arr]
        return newArr.sort().toString()
      } else {
        return arr.toString()
      }
    },
    CountDown (maxtime) {
      let time = maxtime;
      this.timer = setInterval(() => {
        if (time >= 0) {
          let minutes = Math.floor(time / 60);
          let seconds = Math.floor(time % 60);
          if (minutes === 15 && seconds === 0) {
            this.$Modal.info({content: '最后15分钟'})
          }
          // let msg = '距离结束还有' + minutes + '分' + seconds + '秒';
          // if (maxtime === 5 * 60)alert('还剩5分钟');
          this.time = `${minutes < 10 ? 0 : ''}${minutes}:${seconds < 10 ? 0 : ''}${seconds}`;
          --time;
        }
        // else {
        //   clearInterval(this.this);
        //    this.comfirm()
        // }
      }, 1000);
    },
    setTest(data) {
      // debugger
      data.tests.forEach(arr => {
        arr.forEach(item => {
          item.showAnswer = false
          if (item.questype.trim() === '多选题') {
            item.stuquesans = []
          } else {
            item.stuquesans = ''
          }
        })
      })
      this.data = Object.assign({}, data)
      this.timer = setInterval(this.CountDown(parseInt(this.data.usertest.testtimelong) * 60), 1000);
      // this.timer = setInterval(this.CountDown(16 * 60), 1000);
    },
    // 获取题的
    getTestIndex (index, tindex) {
      if (index === 0) {
        return tindex + 1
      } else if (index === 1) {
        return this.data.tests[0].length + tindex + 1
      } else if (index === 2) {
        return this.data.tests[0].length + this.data.tests[1].length + tindex + 1
      }
    },
    idgetTestIndex (data,index, tindex) {
      if (index === 0) {
        var temp= tindex + 1
        return "index" + temp
      } else if (index === 1) {
        var temp= data[0].length + tindex + 1
        return "index" + temp
      } else if (index === 2) {
        var temp= data[0].length + data[1].length + tindex + 1
        return "index" + temp
      }
    },
    maoselect(data,index, tindex){
          // console.log(this.$options.methods.idgetTestIndex(data,index, tindex));
          var anchor = this.$el.querySelector("#"+this.$options.methods.idgetTestIndex(data,index, tindex))
          // console.log(anchor);
          var sTop = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop
          // console.log(sTop);

          // console.log(anchor.offsetTop);
          var div = document.getElementById('body')
          div.scrollTop = anchor.offsetTop
          // document.documentElement.scrollTop = anchor.offsetTop;
    },
    getTotalScore (index) {
      let total = 0
      this.data.tests[index].forEach(item => {
        total += parseInt(item.questionscore)
      })
      return total
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.setTest(to.params)
    })
  },
  watch: {
    'data': {
      handler: function (val, oldVal) {
        this.$lsput('studata', val)
      },
      deep: true
    }
  },
  beforeDestroy () {
    clearInterval(this.this);
    this.$lsdelete('studata')
  }
};
</script>
